from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
import structlog
import sys

from config.settings import settings

from app.middleware.logging import LoggingMiddleware
from app.middleware.rate_limit import RateLimitMiddleware
from app.middleware.auth import AuthMiddleware
from app.routers import gateway, health, dashboard  # 添加dashboard导入

# 配置结构化日志
if settings.debug:
    processors = [
        structlog.stdlib.filter_by_level,
        structlog.stdlib.add_logger_name,
        structlog.stdlib.add_log_level,
        structlog.stdlib.PositionalArgumentsFormatter(),
        structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S"),
        structlog.processors.StackInfoRenderer(),
        structlog.processors.format_exc_info,
        structlog.processors.UnicodeDecoder(),
        structlog.dev.ConsoleRenderer(colors=True)
    ]
else:
    processors = [
        structlog.stdlib.filter_by_level,
        structlog.stdlib.add_logger_name,
        structlog.stdlib.add_log_level,
        structlog.stdlib.PositionalArgumentsFormatter(),
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.StackInfoRenderer(),
        structlog.processors.format_exc_info,
        structlog.processors.UnicodeDecoder(),
        structlog.processors.JSONRenderer()
    ]

structlog.configure(
    processors=processors,
    context_class=dict,
    logger_factory=structlog.stdlib.LoggerFactory(),
    wrapper_class=structlog.stdlib.BoundLogger,
    cache_logger_on_first_use=True,
)

# 确保日志输出到控制台
import logging

logging.basicConfig(
    format="%(message)s",
    stream=sys.stdout,
    level=getattr(logging, settings.log_level.upper(), logging.INFO),
)

logger = structlog.get_logger()

# 创建FastAPI应用
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    description="Suna项目的统一网关服务",
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json"
)

print("🚀 开始添加中间件...")

# 添加中间件 - 关键：正确的顺序
# 最后添加的最先执行，所以顺序是反向的

# 5. CORS中间件 - 最后执行
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=settings.cors_allow_credentials,
    allow_methods=settings.cors_allow_methods,
    allow_headers=settings.cors_allow_headers,
)
print("✅ 添加了CORS中间件")

# 4. 信任主机中间件
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["*"])
print("✅ 添加了TrustedHost中间件")

# 3. 认证中间件 - 关键位置
app.add_middleware(AuthMiddleware)
print("✅ 添加了Auth中间件")

# 2. 限流中间件
app.add_middleware(RateLimitMiddleware)
print("✅ 添加了RateLimit中间件")

# 1. 日志中间件 - 最先执行
app.add_middleware(LoggingMiddleware)
print("✅ 添加了Logging中间件")

print("🔧 中间件执行顺序:")
print(
    "   请求 → LoggingMiddleware → RateLimitMiddleware → AuthMiddleware → TrustedHostMiddleware → CORSMiddleware → 路由处理")

# 初始化服务
from app.services.service_instances import service_discovery, load_balancer


# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(f"💥 全局异常处理: {type(exc).__name__}: {str(exc)}")
    logger.error(
        "Unhandled exception",
        error=str(exc),
        path=request.url.path,
        method=request.method
    )
    return JSONResponse(
        status_code=500,
        content={"detail": "Internal server error"}
    )


# 应用启动事件
@app.on_event("startup")
async def startup_event():
    await service_discovery.start_health_check()
    logger.info("🚀 Gateway启动完成!")
    logger.info(f"📝 调试模式: {settings.debug}")
    logger.info(f"📊 日志级别: {settings.log_level}")
    logger.info(f"🌐 访问Dashboard: http://{settings.host}:{settings.port}/dashboard")
    logger.info("Gateway service started successfully")


# 应用关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    await service_discovery.stop_health_check()
    logger.info("Shutting down Suna Gateway Service")


# 包含路由 - 添加dashboard路由
app.include_router(gateway.router, prefix="/api/v1")
app.include_router(health.router, prefix="/health")
app.include_router(dashboard.router)  # Dashboard路由不需要前缀


# 根路由 - 更新导航信息
@app.get("/", tags=["Root"])
async def root():
    logger.info("Root endpoint accessed")
    return {
        "message": "Welcome to Suna Gateway Service",
        "version": settings.app_version,
        "navigation": {
            "dashboard": "/dashboard",
            "api_docs": "/docs",
            "health_check": "/health",
            "service_status": "/api/v1/services"
        },
        "endpoints": [
            {"path": "/dashboard", "description": "管理仪表板"},
            {"path": "/docs", "description": "API文档"},
            {"path": "/health", "description": "健康检查"},
            {"path": "/api/v1/services", "description": "服务状态"},
            {"path": "/api/dashboard/stats", "description": "仪表板统计"},
        ]
    }


# 测试日志的端点
@app.get("/test-logs", tags=["Debug"])
async def test_logs():
    """测试日志输出"""
    print("🧪 测试日志端点被访问")
    print("🧪 这是控制台输出")
    logger.debug("This is a debug message")
    logger.info("This is an info message")
    logger.warning("This is a warning message")
    logger.error("This is an error message")
    return {"message": "日志测试完成，请检查控制台输出"}


if __name__ == "__main__":
    import uvicorn

    print("🌐 启动Gateway服务...")
    print(f"📊 Dashboard地址: http://{settings.host}:{settings.port}/dashboard")
    uvicorn.run(
        "app.main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        workers=settings.workers if not settings.debug else 1,
        log_level=settings.log_level.lower()
    )